package com.njym.java.security.admin.rest;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.njym.java.security.admin.biz.FamilyUserBiz;
import com.njym.java.security.admin.biz.UserBiz;
import com.njym.java.security.admin.entity.FamilyUser;
import com.njym.java.security.admin.entity.FamilyUserVo;
import com.njym.java.security.admin.entity.User;
import com.njym.java.security.admin.rpc.service.FamilyUserService;
import com.njym.java.security.admin.vo.StatVo;
import com.njym.java.security.common.msg.ObjectRestResponse;
import com.njym.java.security.common.rest.BaseController;
import com.njym.java.security.common.util.ResponseUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("familyUser")
public class FamilyUserController extends BaseController<FamilyUserBiz,FamilyUser> {
    private final Log logger = LogFactory.getLog(FamilyUserController.class);
    @Autowired
    private PlatformTransactionManager txManager;
    @Autowired
    private FamilyUserService familyUserService;

    @Autowired
    private FamilyUserBiz familyUserBiz;
    @Autowired
    private UserBiz userBiz;

    @RequestMapping(value = "/statUser",method = RequestMethod.GET)
    @ResponseBody
    public Object statUser(){
        List<Map> rows = familyUserService.statUser();
        long total  = familyUserService.countUser();
        String[] columns = new String[]{"day", "users"};
        StatVo statVo = new StatVo();
        statVo.setColumns(columns);
        statVo.setRows(rows);
        Map<String, Object> data = new HashMap<>(2);
        data.put("statVo",statVo);
        data.put("total",total);
        return data;
    }

    @RequestMapping(value = "/getList",method = RequestMethod.GET)
    @ResponseBody
    public Object getCount(
            @RequestParam(defaultValue = "10") int limit,
            @RequestParam(defaultValue = "1")int page ,
            String name,
            String mobile,
            String createdTime
    ){
//        if(createdTime != null ) {
//            createdTime = createdTime + " 00:00:00";
//        }
        List<FamilyUser> list = baseBiz.getList(page,limit,name,mobile,createdTime);
        long total = PageInfo.of(list).getTotal();
        Map<String, Object> data = new HashMap<>(2);
        data.put("list", list);
        data.put("total", total);
        return new ObjectRestResponse<>().rel(true).data(data);
    }

    @RequestMapping(value = "/getCount",method = RequestMethod.GET)
    @ResponseBody
    public Object getCount(){
        return baseBiz.getDailiCounts();
    }

    @RequestMapping(value = "/getListAndPercent",method = RequestMethod.GET)
    @ResponseBody
    public Object getListAndPercent(@RequestParam(defaultValue = "1") int page,
                                    @RequestParam(defaultValue = "20") int limit,
                                    Integer teacherId, String name, String mobile){
        PageHelper.startPage(page,limit);
        List<FamilyUserVo> rows = familyUserBiz.getListAndPercent(teacherId, name, mobile);

        int total = familyUserBiz.selectCounts(teacherId, name, mobile);

        Map<String, Object> data = new HashMap<>(2);
        data.put("rows",rows);
        data.put("total",total);
        return data;
    }

    /**
     * 查询家庭主
     * @return
     */
    @RequestMapping(value = "/queryFamilyZhu",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> queryFamilyZhu(){

        List<FamilyUser> list = baseBiz.queryFamilyZhu();
        Map<String, Object> data = new HashMap<>(1);

        data.put("list", list);
        return new ObjectRestResponse<FamilyUser>().rel(true).data(data);

    }

    @RequestMapping(value = "/queryUsers",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> queryUsers(Integer teacherId){

        Example example = new Example(FamilyUser.class);
        example.createCriteria().andEqualTo("teacherId", teacherId);
        List<FamilyUser> list = baseBiz.selectByExample(example);
        Map<String, Object> data = new HashMap<>(1);

        data.put("list", list);
        return new ObjectRestResponse<FamilyUser>().rel(true).data(data);

    }

    @RequestMapping(value = "/querySelective",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> querySelective(Integer teacherId,
        String mobile, String name,
        @RequestParam(defaultValue = "10") int limit,
        @RequestParam(defaultValue = "1")int page){

        Example example = new Example(FamilyUser.class);
        Example.Criteria  criteria = example.createCriteria();
        criteria.andEqualTo("teacherId", teacherId);

        if(name != "" && name != null){
            criteria.andLike("name", "%" + name + "%");
        }
        if(mobile != "" && mobile != null){
            criteria.andLike("mobile", "%" + mobile + "%");
        }

        PageHelper.startPage(page, limit);
        List<FamilyUser> list = baseBiz.selectByExample(example);
        long total = PageInfo.of(list).getTotal();
        Map<String, Object> data = new HashMap<>(2);

        data.put("list", list);
        data.put("total", total);
        return new ObjectRestResponse<FamilyUser>().rel(true).data(data);

    }

    /**
     * 批量导入人员
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/import",method = RequestMethod.POST)
    @ResponseBody
    public Object importAll(@RequestBody Object data) {
        FamilyUser familyUser = new FamilyUser();

        Map<String, String> map = (Map<String, String>) data;
        //获取excel中数据
        String name = map.get("name");
        String nickName = map.get("nickName");
        String mobile = map.get("mobile");
        String sex = map.get("sex");
        String email = map.get("email");

        if (name == null || mobile == null) {
            String a = "主要信息不能为空";
            return ResponseUtil.ok(a);
        } else {
            familyUser.setName(name);
            familyUser.setNickName(nickName);
            familyUser.setMobile(mobile);
            //判断excel中性别  转化为数字
            if(sex == null){
                familyUser.setSex(null);
            }else{
                Integer sexs;
                if(sex.equals("男")){
                    sexs = 1;
                }
                else if(sex.equals("女")){
                    sexs = 2;
                }else{
                    sexs = 0;
                }
                familyUser.setSex(sexs);
            }

            familyUser.setEmail(email);
            //密码加密
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodedPassword = encoder.encode("123456");
            familyUser.setPassword(encodedPassword);

            Example example = new Example(FamilyUser.class);
            example.createCriteria().andEqualTo("mobile", mobile);

            List<FamilyUser> user = familyUserBiz.selectByExample(example);
            if (user.size() > 0) {
                return ResponseUtil.ok(data);
            }
            // 开启事务管理
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            TransactionStatus status = txManager.getTransaction(def);


            try {
                familyUserBiz.insert(familyUser);
            }
            catch (Exception ex) {
                txManager.rollback(status);
                return ResponseUtil.ok();
            }
            txManager.commit(status);
            ((Map<String, Object>)data).put("count", "0");

            return ResponseUtil.ok(data);
        }
    }

    @RequestMapping(value = "/queryIndirect",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> queryIndirect(@RequestParam(defaultValue = "10") int limit,
        @RequestParam(defaultValue = "1")int page){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String dates = sdf.format(date);
        String start = dates + " 00:00:00";
        String end = dates + " 23:59:59";
        List<FamilyUser> list = baseBiz.queryIndirect(start, end, page, limit);
        long total = PageInfo.of(list).getTotal();

        Map<String, Object> data = new HashMap<>(2);
        data.put("list", list);
        data.put("total", total);

        return new ObjectRestResponse<FamilyUser>().rel(true).data(data);

    }


    @RequestMapping(value = "/query365",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> query365(@RequestParam(defaultValue = "10") int limit,
        @RequestParam(defaultValue = "1")int page){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String dates = sdf.format(date);
        String start = dates + " 00:00:00";
        String end = dates + " 23:59:59";
        List<FamilyUser> list = baseBiz.query365(start, end);
        long total = PageInfo.of(list).getTotal();

        Map<String, Object> data = new HashMap<>(2);
        data.put("list", list);
        data.put("total", total);

        return new ObjectRestResponse<FamilyUser>().rel(true).data(data);

    }

    @RequestMapping(value = "/querydaili",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> querydaili(String mobile){
        Example example = new Example(FamilyUser.class);
        example.createCriteria().andEqualTo("mobile", mobile);
        List<FamilyUser> list = baseBiz.selectByExample(example);
        if(list.size() > 0) {
            Example example1 = new Example(FamilyUser.class);
            example1.createCriteria().andEqualTo("id", list.get(0).getTeacherId());
            List<User> user = userBiz.selectByExample(example1);
            if (user.size() > 0){
                User u = user.get(0);
                if (u.getAttr5().equals("1")){
                    return new ObjectRestResponse<FamilyUser>().rel(true).data(u);
                }
            }
        }
        Map<String, Object> data = new HashMap<>(2);


        return new ObjectRestResponse<FamilyUser>().rel(true).data(data);

    }

    @RequestMapping(value = "/queryDaiLiRegister",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUserVo> queryDaiLiRegister(String start, String end,
        @RequestParam(defaultValue = "10") int limit,
        @RequestParam(defaultValue = "1")int page){
        if(start != null && end != null) {
            start = start + " 00:00:00";
            end = end + " 23:59:59";
        }

        List<FamilyUserVo> list = familyUserBiz.queryDaiLiRegister(start, end, page, limit);
        long total = PageInfo.of(list).getTotal();

        Map<String, Object> data = new HashMap<>(2);
        data.put("list", list);
        data.put("total", total);

        return new ObjectRestResponse<FamilyUserVo>().rel(true).data(data);

    }

    @RequestMapping(value = "/queryDaiLiRegisterAll",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUserVo> queryDaiLiRegisterAll(String start, String end
        ){
        if(start != null && end != null) {
            start = start + " 00:00:00";
            end = end + " 23:59:59";
        }

        List<FamilyUserVo> list = familyUserBiz.queryDaiLiRegisterAll(start, end);


        Map<String, Object> data = new HashMap<>(2);
        data.put("list", list);

        return new ObjectRestResponse<FamilyUserVo>().rel(true).data(data);

    }

    @RequestMapping(value = "/queryNoRegister",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> queryNoRegister(String start, String end,
        @RequestParam(defaultValue = "10") int limit,
        @RequestParam(defaultValue = "1")int page){
        if(start != null && end != null) {
            start = start + " 00:00:00";
            end = end + " 23:59:59";
        }

        List<FamilyUser> list = familyUserBiz.queryNoRegister(start, end, page, limit);
        long total = PageInfo.of(list).getTotal();

        Map<String, Object> data = new HashMap<>(2);
        data.put("list", list);
        data.put("total", total);

        return new ObjectRestResponse<FamilyUser>().rel(true).data(data);

    }

    @RequestMapping(value = "/queryNoRegisterAll",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> queryNoRegisterAll(String start, String end
    ){
        if(start != null && end != null) {
            start = start + " 00:00:00";
            end = end + " 23:59:59";
        }

        List<FamilyUser> list = familyUserBiz.queryNoRegisterAll(start, end);


        Map<String, Object> data = new HashMap<>(2);
        data.put("list", list);

        return new ObjectRestResponse<FamilyUser>().rel(true).data(data);

    }

    /**
     * 普通用户推广的数据
     * @param limit
     * @param page
     * @param name
     * @param mobile
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryJianJie", method = RequestMethod.GET)
    @ResponseBody
    public Object queryTeacherDetail(@RequestParam(defaultValue = "10") int limit,
                                     @RequestParam(defaultValue = "1")int page,
                                     String name, String mobile) throws Exception {
        List<FamilyUserVo> list = baseBiz.getZhiJieCount(page,limit,name,mobile);
        long total = PageInfo.of(list).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("list",list);
        data.put("total",total);
        return ResponseUtil.ok(data);

    }
}